package com.xiaoke.api.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiaoke.api.service.OrderService;
import com.xiaoke.api.service.PayService;
import com.xiaoke.entity.Order;
import com.xiaoke.util.common.AjaxMsg;
import com.xiaoke.util.common.ValidUtil;
import com.xiaoke.util.pay.WXConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/pay")
public class PayController {
    private static Logger logger = LoggerFactory.getLogger(PayController.class);
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private WXConfig wxConfig;

    @PostMapping("/prepay")
    public AjaxMsg prepay(String orderId, String openId) throws Exception {
        if (ValidUtil.isEmpty(orderId, openId))
            return new AjaxMsg(AjaxMsg.FAILURE, "参数缺失！");
        Order order = orderService.selectByPrimaryKey(orderId);
        if (order == null)
            return new AjaxMsg(AjaxMsg.FAILURE, "订单不存在！");

        WXPay wxPay = new WXPay(wxConfig);
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", order.getOrderSn());
        data.put("total_fee", order.getActualPrice() + "");
        data.put("openid", openId);
        data.put("trade_type", "JSAPI");
        data.put("spbill_create_ip", wxConfig.getSpbillCreateIp());
        data.put("notify_url", wxConfig.getNotifyUrl());
        data.put("body", order.getOrderSn());

        Map<String, String> resp = null;
        String prepay_id = null;
        try {
            logger.info("微信统一下单参数：{}", data.toString());
            resp = wxPay.unifiedOrder(data);
            if (resp.get("return_code") != null && resp.get("return_code").equals("SUCCESS")) {
                if (resp.get("result_code").equals("SUCCESS")) {
                    prepay_id = resp.get("prepay_id");
                }
                if (resp.get("result_code").equals("FAIL")) {
                    logger.error("微信统一下单失败：" + resp.toString());
                    return new AjaxMsg(AjaxMsg.FAILURE, "微信下单失败!");
                }
            } else {
                logger.error("微信统一下单失败：" + resp.toString());
                return new AjaxMsg(AjaxMsg.FAILURE, "微信下单失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信统一下单失败");
        }

        String timeStamp = new Date().getTime() / 1000 + "";
        Map<String, String> map = new HashMap<String, String>();
        map.put("appId", wxConfig.getAppID());
        map.put("nonceStr", WXPayUtil.generateNonceStr());
        map.put("package", "prepay_id=" + prepay_id);
        map.put("signType", "MD5");
        map.put("timeStamp", timeStamp);
        map.put("paySign", WXPayUtil.generateSignature(map, wxConfig.getKey()));

        return new AjaxMsg(map);
    }

    @RequestMapping(value = "/wxNotify")
    public String wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("-------收到微信通知---------");
        //读取参数
        BufferedReader reader = null;
        reader = request.getReader();
        String line = "";
        String xmlString = null;
        StringBuffer inputString = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        logger.info("微信回调信息：" + xmlString);

        Map<String, String> map = WXPayUtil.xmlToMap(xmlString);
        String wxKey = wxConfig.getKey();
        //验签
        if (WXPayUtil.isSignatureValid(map, wxKey/*wxConfig.getKey()*/)) {
            //验签通过
            String out_trade_no = map.get("out_trade_no");
            String total_fee = map.get("total_fee");

            logger.info("支付成功");
            orderService.buySuccess(out_trade_no, map.get("result_code"));
            //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
            return returnXML(map.get("result_code"));

        } else {
            logger.info("支付失败,错误信息：" + map.get("err_code"));
            // 验签失败
            return returnXML("FAIL");
        }

    }


    private String returnXML(String return_code) {

        return "<xml><return_code><![CDATA["

                + return_code

                + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }
}